﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;

namespace ExpLib.Core.Tools
{
    public class EnumDataSource
    {
        Type m_EnumType = null;

        public EnumDataSource(Type enumType)
        {
            if (enumType.IsEnum != true)
                throw new InvalidOperationException();

            this.m_EnumType = enumType;
        }

        /// <summary>
        /// 将一个枚举做为一个数据源
        /// </summary>
        /// <returns></returns>
        public List<KeyValuePair<String, int>> GetItems()
        {
            // 获得特性Description的类型信息 

            List<KeyValuePair<String, int>> collection = new List<KeyValuePair<String, int>>();

            Type typeDescription = typeof(DescriptionAttribute);
            System.Reflection.FieldInfo[] fields = m_EnumType.GetFields();
            


            foreach (FieldInfo field in fields)
            {
                // 过滤掉一个不是枚举值的，记录的是枚举的源类型 
                if (field.FieldType.IsEnum == false)
                    continue;

                // 通过字段的名字得到枚举的值 
                int value = (int)m_EnumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null);
                string text = string.Empty;


                object[] arr = field.GetCustomAttributes(typeDescription, true);
                if (arr.Length > 0)
                {
                    // 因为Description自定义特性不允许重复，所以只取第一个 
                    DescriptionAttribute aa = (DescriptionAttribute)arr[0];
                    // 获得特性的描述值 
                    text = aa.Description;
                }
                else
                {
                    // 如果没有特性描述，那么就显示英文的字段名 
                    text = field.Name;
                }

                collection.Add(new KeyValuePair<String,int>(text,value));
            }
            return collection;
        }

        /// <summary>
        /// 根据值取得描述信息
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static string GetDescription(Enum enumType)
        {
            Type type = enumType.GetType();
            FieldInfo fd = type.GetField(enumType.ToString());

            if (fd == null) 
                return string.Empty;

            object[] attrs = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
            string name = string.Empty;

            foreach (DescriptionAttribute attr in attrs)
            {
                name = attr.Description;
            }
            return name;
        }
    }
}
